package com.zx.sercurity;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

public abstract class AsyncRiskControlAbs<T> implements AsyncRiskInterface<T>, DefaultLifecycleObserver {

    protected static final String TAG = "AsyncRiskControl";

    protected ScheduledExecutorService service;
    protected ScheduledFuture<?> schedule;
    protected final AsyncRiskListener listener;

    public AsyncRiskControlAbs(AsyncRiskListener listener) {
        this.listener = listener;
    }

    /**
     * 获取线程池，必要时重建
     */
    protected ScheduledExecutorService getService() {
        if (service == null || service.isShutdown()) {
            synchronized (AsyncRiskControlAbs.class) {
                if (service == null || service.isShutdown()) {
                    Log.d(TAG, "Creating new ScheduledExecutorService");
                    service = Executors.newSingleThreadScheduledExecutor();
                }
            }
        }
        return service;
    }

    /**
     * 取消当前任务，但保留线程池，用于可重启倒计时
     */
    @Override
    public void stopCheck() {
        Log.i(TAG, "StopCheck: " + this.getClass().getSimpleName());
        if (schedule != null && !schedule.isCancelled()) {
            schedule.cancel(true);
            schedule = null;
        }
    }

    /**
     * 完全销毁，释放线程池与任务
     */
    @Override
    public void destroy() {
        Log.w(TAG, "Destroy: " + this.getClass().getSimpleName());
        stopCheck();
        if (service != null && !service.isShutdown()) {
            service.shutdownNow();
            service = null;
        }
    }

    /**
     * 生命周期回调绑定销毁逻辑
     */
    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        destroy();
    }
}
